import 'package:carousel_slider/carousel_slider.dart';
import 'package:easy_rich_text/easy_rich_text.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:gradient_borders/box_borders/gradient_box_border.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_page/main_page/provider/msg_provider.dart';
import 'package:xvideos/hj_page/mine_business/mine_utils.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/charge_user_header.dart';
import 'package:xvideos/hj_page/mine_business/mine_vip/vip_card_item.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_alert.dart';
import 'package:xvideos/hj_page/pre_sale/pre_sale_provider.dart';
import 'package:xvideos/hj_utils/screen.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';

import '../make_money/mine_withdrawal_record_page.dart';
import 'mine_charge_vip_logic.dart';

class MineChargeVipPage extends StatelessWidget {
  static const String routeName = '/charge/vip';
  const MineChargeVipPage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MineChargeVipLogic>(
      init: MineChargeVipLogic(),
      builder: (controller) => Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          elevation: 0,
          backgroundColor: Colors.transparent,
          iconTheme: IconThemeData(color: Colors.white),
          title: Text(
            '会员中心',
            style: TextStyle(color: Colors.white),
          ),
          actions: [
            InkWell(
              onTap: () => Get.to(RecordsPage(RecordType.withdraw)),
              child: Text(
                '充值记录',
                style: TextStyle(color: Colors.white.withOpacity(.45), fontSize: 12),
              ),
            ),
            16.sizeBoxW,
          ],
        ),
        body: () {
          if (controller.isLoading) return LoadingCenterWidget();
          if (controller.dataSource.isEmpty) return CErrorWidget();
          return Stack(
            children: [
              Image.asset(
                'mine_bg.webp'.mineImgPath,
                width: double.infinity,
                fit: BoxFit.cover,
              ),
              Column(
                children: [
                  (kToolbarHeight + screen.paddingTop).sizeBoxH,
                  // 会员卡实体
                  Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          12.sizeBoxH,
                          UserChargeView(),
                          26.sizeBoxH,
                          // 会员卡列表
                          CarouselSlider.builder(
                            carouselController: controller.pageCtr,
                            itemCount: controller.dataSource.length,
                            itemBuilder: (_, index, __) => controller.instanceChildItem(index),
                            options: CarouselOptions(
                              height: controller.cardHeight,
                              viewportFraction: controller.itemRatio,
                              initialPage: 0,
                              enableInfiniteScroll: true,
                              reverse: false,
                              autoPlay: false,
                              enlargeCenterPage: true,
                              onPageChanged: (index, __) => controller.onPageChanged(index),
                              scrollDirection: Axis.horizontal,
                            ),
                          ),
                          14.sizeBoxH,
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 16),
                            width: double.infinity,
                            padding: EdgeInsets.symmetric(horizontal: 23),
                            height: 54,
                            alignment: Alignment.centerLeft,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(12),
                                topRight: Radius.circular(12),
                              ),
                              border: GradientBoxBorder(
                                gradient: LinearGradient(
                                  colors: [
                                    Colors.white.withOpacity(.4),
                                    Colors.white.withOpacity(0),
                                  ],
                                  begin: Alignment.topCenter,
                                  end: Alignment.bottomCenter,
                                ),
                                width: 1,
                              ),
                            ),
                            child: Image.asset(
                              'vip_recommend.png'.mineImgPath,
                              width: 89,
                            ),
                          ),
                          12.sizeBoxH,
                          //会员权益
                          GridView.builder(
                            padding: EdgeInsets.symmetric(horizontal: 19.5),
                            shrinkWrap: true,
                            physics: NeverScrollableScrollPhysics(),
                            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: 4,
                              mainAxisSpacing: 12,
                              crossAxisSpacing: 24,
                              childAspectRatio: 66 / 82,
                            ),
                            itemCount: controller.currentProductModel?.newPrivilege?.length ?? 0,
                            itemBuilder: (BuildContext context, int index) {
                              final privilege = controller.currentProductModel?.newPrivilege![index];
                              return VipProductPrivilegeItem(privilege);
                            },
                          ),
                          100.sizeBoxH,
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: _buildPay(controller), //  支付相关
              )
            ],
          );
        }(),
      ),
    );
  }

  Widget _buildNewVip() {
    if (globalStore.isVIP()) return Container();
    return Consumer<MineMsgProvider>(builder: (context, provider, child) {
      if ((provider.countdown?.leftTimeSinceEpoch ?? 0) <= 0) {
        return Container();
      }
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 16),
        child: Stack(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.asset(
                'mine_vip_bg.png'.mineImgPath,
                height: 50,
                width: double.infinity,
                fit: BoxFit.fill,
              ),
            ),
            Positioned.fill(
              child: Row(
                children: [
                  15.sizeBoxW,
                  Image.asset(
                    'vip1.png'.mineImgPath,
                    height: 36,
                  ),
                  6.sizeBoxW,
                  Padding(
                    padding: EdgeInsets.only(bottom: 2),
                    child: Text(
                      '新人限时特惠',
                      style: TextStyle(color: Colors.white, fontSize: 18),
                    ),
                  ),
                  16.sizeBoxW,
                  ...constructTime(provider.countdown?.leftTimeSinceEpoch ?? 0),
                ],
              ),
            ),
          ],
        ),
      );
    });
  }

  List<Widget> constructTime(int seconds) {
    int day = seconds ~/ (3600 * 24);
    int hour = seconds % (3600 * 24) ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = seconds % 60;
    if (day > 0) {
      return [
        _buildNumWidget(formatTime(day).toString()),
        _buildContentWidget('天'),
        _buildNumWidget(formatTime(hour).toString()),
        _buildContentWidget('时'),
        _buildNumWidget(formatTime(minute).toString()),
        _buildContentWidget('分'),
        _buildNumWidget(formatTime(second).toString()),
        _buildContentWidget('秒'),
      ];
    }
    return [
      _buildNumWidget(formatTime(hour).toString()),
      _buildContentWidget('时'),
      _buildNumWidget(formatTime(minute).toString()),
      _buildContentWidget('分'),
      _buildNumWidget(formatTime(second).toString()),
      _buildContentWidget('秒'),
    ];
  }

  Widget _buildContentWidget(String content) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        content,
        style: TextStyle(fontSize: 10, color: Colors.white),
      ),
    );
  }

  Widget _buildNumWidget(String content) {
    return Container(
      width: 20,
      height: 20,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(3),
      ),
      child: Center(
        child: Text(
          content,
          style: TextStyle(fontSize: 12, color: Color(0xFFF36E6E)),
        ),
      ),
    );
  }

  String formatTime(int timeNum) {
    return timeNum < 10 ? "0$timeNum" : timeNum.toString();
  }

  _buildPay(MineChargeVipLogic controller) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [
            Colors.black.withOpacity(0),
            Colors.black,
          ],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          12.sizeBoxH,
          () {
            if (controller.currentProductModel?.isPreSale == true)
              return PreSaleActivityButton(onTap: () => PreSaleProvider().onInitiatePayAction(controller.currentProductModel!));
            return GestureDetector(
              onTap: controller.onInitiatePayAction,
              child: Container(
                height: 44,
                margin: EdgeInsets.symmetric(horizontal: 20),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(3),
                  color: AppColors.actionRed,
                ),
                child: Text(
                  '¥${(controller.currentProductModel?.discountedPrice ?? 0) ~/ 10}/立即支付',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            );
          }(),
          12.sizeBoxH,
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16),
            child: EasyRichText(
              '支付问题反馈，点击联系 在线客服',
              patternList: [
                EasyRichTextPattern(
                  targetString: '在线客服',
                  style: TextStyle(
                    color: Color(0xFFFFD460),
                    fontSize: 12,
                  ),
                  recognizer: TapGestureRecognizer()..onTap = () => MineUtils.goCSPage(),
                )
              ],
              defaultStyle: TextStyle(color: Color(0xffDCDCDC), fontSize: 12),
            ),
          ),
          12.sizeBoxH,
        ],
      ),
    );
  }
}
